package com.example.myapplication.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

@Composable
fun Counter(padding: PaddingValues, modifier: Modifier = Modifier) {
    //定义可观察的状态变量，并使用remember记住该状态；
    var counter by rememberSaveable { mutableIntStateOf(0) }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
        modifier = modifier
            .background(Color.Yellow)
            .fillMaxWidth()
            .padding(padding)
    ) {
        Text(text = "当前计数：$counter", fontSize = 24.sp)

        Row {
            Button(onClick = { counter++ }, modifier = Modifier.padding(8.dp)) {
                Text("增加")
            }
            Button(onClick = { counter-- }, modifier = Modifier.padding(8.dp)) {
                Text("减少")
            }
        }
    }
}

@Composable
fun RememberSaveable(padding: PaddingValues){
    var flag by rememberSaveable { mutableStateOf(true) }
    Column(
        modifier = Modifier.fillMaxSize()
            .padding(padding)
    ) {
        if (flag){
            Counter(padding)
        }

        Button(onClick = {
            flag= !flag
        }) {
            Text("隐藏显示计数器")
        }
    }
}